# Create your views here.
from django.template import Context, loader
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, Http404, HttpResponseRedirect
from homework.models import Homework, HomeworkUpload, UserProfile, NewsItem, Course, RegistrationForm
from django.contrib.auth.models import User
from django import forms
import time, datetime
from time import strftime, localtime
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.syndication.feeds import Feed

@login_required
def index(request):
	username = request.user.username
	u = User.objects.get(username=username)
	userperms = u.get_profile().permissions
	news = NewsItem.objects.order_by('-date')[:3]	

	if userperms == 'TE':
		is_teacher = True
		return render_to_response('homework/index.html', {'username': u, 'is_teacher': is_teacher, 'news': news})
	else:
		is_student = True
		return render_to_response('homework/index.html', {'username': u, 'is_student': is_student, 'news': news}) 
	

@login_required
def hwklist(request):
    username = request.user.username
    u = User.objects.get(username=username)
    userperms = u.get_profile().permissions
    classesjoined =  u.get_profile().courses
    if request.GET:
	if request.GET['sort'] == 'asc':
		object_list = Homework.objects.filter(course__in = list(classesjoined.all())).order_by('-duedate')[:100]
		c = Context({
		        'object_list': object_list,
		})
    else:
	object_list = Homework.objects.filter(course__in = list(classesjoined.all())).order_by('duedate')[:100]
       	c = Context({
		'object_list': object_list,
    	})
    t = loader.get_template('homework/homework_list.html')
    return HttpResponse(t.render(c))

@login_required
def detail(request, object_id):
	try:
		h = Homework.objects.get(pk=object_id)
	except Homework.DoesNotExist:
		return render_to_response('homework/detail_404.html', {'object_id': object_id })
	return render_to_response('homework/homework_detail.html', {'homework': h})

@login_required
def uploadfile(request):
	manipulator = HomeworkUpload.AddManipulator()
        username = request.user.username
        u = User.objects.get(username=username)

	if request.POST:
	# New upload if data was POSTed.
		new_data = request.POST.copy()
		new_data.update(request.FILES)
		print(request.user.username)
		new_data['uptime_date'] = datetime.date.today().isoformat()
		new_data['uptime_time'] = strftime("%H:%M", localtime())	
		new_data['owner'] = u.id
		errors	= manipulator.get_validation_errors(new_data)	
		print(errors)
		if not errors:
		# No errors found.
			manipulator.do_html2python(new_data)
			manipulator.save(new_data)
			success = "File uploaded"
	                return render_to_response('homework/success.html', {'success': success})

		else:
		# Errors found, not writing to database.
			errorstring = "<br />".join(errors)
			return render_to_response('homework/uploadfail.html', {'errorstring': errorstring}) 
			errors = new_data = {}  # Errors sent to the template, can be cleared.
	else:
	# No data POSTed, redirect to /hwk
		return HttpResponseRedirect("/hwk")


@login_required	
def upload(request, object_id):
	manipulator = HomeworkUpload.AddManipulator()
	h = Homework.objects.get(pk=object_id)	
	form = forms.FormWrapper(manipulator,{},{})
	return render_to_response('homework/homeworkbin.html', {'form': form, 'homework': h} )

def logon(request):
    if request.user.is_authenticated():
	return HttpResponseRedirect('/hwk')
    else:
    	username = request.POST['username']
    	password = request.POST['password']
    	user = authenticate(username=username, password=password)
    	if user is not None:
		login(request, user)
		return HttpResponseRedirect("/hwk")
    	else:
    		HttpResponse("Not logged in")

def unlogon(request):
	logout(request)
	return HttpResponse("Succesfully logged out")

@login_required
def uploadlist(request):
    username = request.user.username
    u = User.objects.get(username=username)
    userperms = u.get_profile().permissions
    classesjoined =  u.get_profile().courses
	
    if userperms == 'ST':
	homework_upload = HomeworkUpload.objects.filter(homeworkid__in = list(classesjoined.all())).filter(owner__exact = u)
	is_teacher = False
    else:
        homework_upload = HomeworkUpload.objects.all()
	is_teacher = True
    print(homework_upload)

    return render_to_response('homework/file_list.html', {'homework_upload': homework_upload, 'is_teacher': is_teacher})


@login_required
def addhwk(request):
    username = request.user.username
    u = User.objects.get(username=username)
    userperms = u.get_profile().permissions
    
    if userperms == 'TE':
	manipulator = Homework.AddManipulator()
	form = forms.FormWrapper(manipulator,{},{})   
	return render_to_response('homework/addhwk.html', {'form': form})

    else:
	return render_to_response('homework/unauthorised.html')
	
@login_required
def newhwk(request):
  manipulator = Homework.AddManipulator()
  username = request.user.username
  u = User.objects.get(username=username)
  userperms = u.get_profile().permissions

  if userperms == 'TE':

 	if request.POST:
        # New upload if data was POSTed.
	   new_data = request.POST.copy()
	   errors = manipulator.get_validation_errors(new_data)	
 	   print(errors)
	
 	   if not errors:
		manipulator.do_html2python(new_data)
		manipulator.save(new_data)
		success = "New homework added"
                return render_to_response('homework/success.html', {'success': success})

	   else:
		errorstring = "<br />".join(errors)
		return render_to_response('homework/uploadfail.html', {'errorstring': errorstring})
		errors = new_data = {}
  	else:
	   return HttpResponseRedirect("/hwk")
  else:
	return render_to_response('homework/unauthorised.html')


@login_required
def addnews(request):
  manipulator = NewsItem.AddManipulator()
  username = request.user.username
  u = User.objects.get(username=username)
  userperms = u.get_profile().permissions

  
  if request.POST:
	if userperms == 'TE':
   	   # Upload new item.
	   new_data = request.POST.copy()
           new_data['author'] = u.id
	   errors = manipulator.get_validation_errors(new_data)

	   if not errors: 
		manipulator.do_html2python(new_data)
		manipulator.save(new_data)
		success = "News item added"
		return render_to_response('homework/success.html', {'success': success})
	
	   else:
		print(errors)
		errorstring = "<br />".join(errors)
		return render_to_response('homework/uploadfail.html', {'errorstring': errorstring})
		errors = new_data = {}

	else:
	   return render_to_response('homework/unauthorised.html')
  else:
	return HttpResponseRedirect("/hwk")

@login_required
def viewnews(request, object_id):
	try:
               n = NewsItem.objects.get(pk=object_id)
        except NewsItem.DoesNotExist:
                return render_to_response('homework/404.html', {'object_id': object_id })
        return render_to_response('homework/viewnews.html', {'news': n})

@login_required
def newnews(request):
    username = request.user.username
    u = User.objects.get(username=username)
    userperms = u.get_profile().permissions

    if userperms == 'TE':
        manipulator = NewsItem.AddManipulator()
        form = forms.FormWrapper(manipulator,{},{})
        return render_to_response('homework/newnews.html', {'form': form})

    else:
	return render_to_response('homework/unauthorised.html')

@login_required
def newclass(request):
    username = request.user.username
    u = User.objects.get(username=username)
    userperms = u.get_profile().permissions

    if userperms == 'TE':
        manipulator = Course.AddManipulator()
        form = forms.FormWrapper(manipulator,{},{})
        return render_to_response('homework/newclass.html', {'form': form})

    else:
        return render_to_response('homework/unauthorised.html')

@login_required
def addclass(request):
  manipulator = Course.AddManipulator()
  username = request.user.username
  u = User.objects.get(username=username)
  userperms = u.get_profile().permissions

  if request.POST:
        if userperms == 'TE':
           # Upload new item.
           new_data = request.POST.copy()
           errors = manipulator.get_validation_errors(new_data)

           if not errors:
                manipulator.do_html2python(new_data)
                manipulator.save(new_data)
		success = "Class added"
                return render_to_response('homework/success.html', {'success': success})
           else:
                print(errors)
                errorstring = "<br />".join(errors)
                return render_to_response('homework/uploadfail.html', {'errorstring': errorstring})
                errors = new_data = {}

        else:
           return render_to_response('homework/unauthorised.html')
  else:
        return HttpResponseRedirect("/hwk")

@login_required
def register(request):
  username = request.user.username
  u = User.objects.get(username=username)
  userperms = u.get_profile().permissions

  if userperms == 'ST':
	return render_to_response('homework/unauthorised.html')

  manipulator = RegistrationForm()
  manipulatorprofile = UserProfile.AddManipulator()
  if request.POST:
	new_data = request.POST.copy()
	errors = manipulator.get_validation_errors(new_data)
	if not errors:
	    permissions = new_data['permissions']
	    manipulator.do_html2python(new_data)
	    new_user = manipulator.save(new_data)

	    coursesnew = new_data.getlist('courses')
            courses = Course.objects.filter(id__in = list(coursesnew))
	    new_profile = UserProfile(permissions=permissions,
				      user=new_user)

	    new_profile.courses = courses
	    new_profile.save()
	    success = "User added" 
      	    return render_to_response('homework/success.html', {'success': success})
	else:
	    errorstring = "<br />".join(errors)
	    return render_to_response('homework/uploadfail.html', {'errorstring': errorstring})
  else:
	errors = new_data = new_data = {}

  form = forms.FormWrapper(manipulator, new_data, errors)
  formprofile = forms.FormWrapper(manipulatorprofile, new_data, errors)
  return render_to_response('homework/register.html', {'form': form, 'formprofile': formprofile})

class SiteNewsFeed(Feed):
   title = "Latest homework"
   link = "/latest/"
   description = "Latest homework additions"

   def items(self):
	return Homework.objects.order_by('-pub_date')[:10]
	    


